package com.shuke.my_test.tree_lazy.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shuke.my_test.tree_lazy.domain.LabelType;
import com.shuke.my_test.tree_lazy.domain.vo.CurrentPackVO;
import com.shuke.my_test.tree_lazy.domain.vo.LabelTypeVO;
import com.shuke.my_test.tree_lazy.mapper.LabelTypeMapper;
import com.shuke.my_test.tree_lazy.service.LabelTypeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 舒克、舒克
 * @date 2025/5/6 17:03
 * @description
 */
@Service
public class LabelTypeServiceImpl implements LabelTypeService {

    @Resource
    private LabelTypeMapper labelTypeMapper;

    /**
     * 获取子节点并计算是否有下级
     */
    @Override
    public List<LabelTypeVO> getChildrenWithStatus(Integer parentId) {
        // 1. 查询直接子节点
        List<LabelType> children = labelTypeMapper.selectList(
                new QueryWrapper<LabelType>()
                        .eq("parent_id", parentId)
                        .orderByAsc("id")
        );

        // 2. 转换为VO并计算hasChildren
        return children.stream().map(entity -> {
            LabelTypeVO vo = new LabelTypeVO();
            BeanUtil.copyProperties(entity, vo);
            vo.setHasChildren(hasChildren(entity.getId()));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 判断是否存在子节点（性能优化版）
     */
    private boolean hasChildren(Integer id) {
        return labelTypeMapper.exists(

                new QueryWrapper<LabelType>()
                        .eq("parent_id", id)
                        .last("LIMIT 1")
        );
    }


    @Override
    public List<CurrentPackVO> newCurrentPack(Integer psId) {
        // 1. 获取电站下所有电池仓（第1级）
        List<LabelType> cabins = labelTypeMapper.selectList(
                new QueryWrapper<LabelType>().eq("parent_id", psId));
        if (cabins.isEmpty()) return Collections.emptyList();

        // 2. 批量查询所有层级数据（总4次查询）
        Map<Integer, List<LabelType>> cabinToBms = batchGetChildren(getIdSet(cabins));
        Set<Integer> bmsIds = getIdSet( flatten(cabinToBms.values()) ); // 新增扁平化方法调用

        Map<Integer, List<LabelType>> bmsToRack = batchGetChildren(bmsIds);
        Set<Integer> rackIds = getIdSet( flatten(bmsToRack.values()) );

        Map<Integer, List<LabelType>> rackToPack = batchGetChildren(rackIds);

        // 3. 内存构建VO结构
        List<CurrentPackVO> result = new ArrayList<>();
        cabins.forEach(cabin ->
                cabinToBms.getOrDefault(cabin.getId(), Collections.emptyList())
                        .forEach(bms ->
                                {
                                    List<LabelType> rackList = bmsToRack.getOrDefault(bms.getId(), Collections.emptyList());
                                    rackList.forEach(rack -> {
                                                int  rackId = rackList.indexOf(rack) + 1;
                                                List<LabelType>   packList =  rackToPack.getOrDefault(rack.getId(), Collections.emptyList());
                                                packList.forEach(pack -> {
                                                    int  packId = packList.indexOf(pack) + 1;
                                                            result.add(createVO(cabin, bms, rack, pack,rackId,packId));
                                                        }

                                                        );
                                                    }
                                            );
                                }
                        )
        );
        return result;
    }

    private CurrentPackVO createVO(LabelType cabin, LabelType bms, LabelType rack, LabelType pack,
                                   Integer rackIndex , Integer packIndex) {

        CurrentPackVO currentPack = new CurrentPackVO();
        currentPack.setCabinNo(cabin.getId());
        currentPack.setBoxNo(bms.getId());
        currentPack.setRackNo(rackIndex);
        currentPack.setPackNo(packIndex);
        currentPack.setRackId(rack.getId());
        currentPack.setPackId(pack.getId());
        return currentPack;
    }

    private Collection<LabelType> flatten(Collection<List<LabelType>> nestedCollection) {
        return nestedCollection.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }

    // 辅助方法：批量获取子节点
    private Map<Integer, List<LabelType>> batchGetChildren(Set<Integer> parentIds) {
        if (parentIds.isEmpty()) return Collections.emptyMap();
        List<LabelType> list = labelTypeMapper.batchSelectByParent(parentIds);
        return list.stream().collect(Collectors.groupingBy(LabelType::getParentId));
    }

    // 辅助方法：提取ID集合
    private Set<Integer> getIdSet(Collection<LabelType> nodes) {
        return nodes.stream().map(LabelType::getId).collect(Collectors.toSet());
    }
}
